<template>
    <div>
        <!-- 查询表单 -->
        <a-card :bordered="false">
            <a-form :model="searchForm" layout="inline" @finish="handleSearch">
                <a-form-item label="标题" name="title">
                    <a-input v-model:value="searchForm.name" placeholder="请输入分类关键词" allow-clear />
                </a-form-item>
                <a-form-item label="代码" name="code">
                    <a-input v-model:value="searchForm.code" placeholder="请输入代码关键词" allow-clear />
                </a-form-item>

                <a-form-item>
                    <a-space>
                        <a-button type="primary" html-type="submit">查询</a-button>
                        <a-button @click="handleReset">重置</a-button>
                    </a-space>
                </a-form-item>
            </a-form>
        </a-card>
        <!-- 表格 -->
        <a-card :bordered="false" class="mt-4">
            <a-button type="primary" @click="handleAdd" class="mb-4">新增</a-button>

            <a-table
                :columns="columns"
                :data-source="data.data.list"
                :pagination="pagination"
                :loading="loading"
                @change="handleTableChange"
            >
                <template #bodyCell="{ column, record }">
                    <!-- 操作列 -->
                    <template v-if="column.dataIndex === 'action'">
                        <a-space :size="8">
                            <a-button type="link" size="small" @click="handleEdit(record as any)"> 编辑 </a-button>
                            <!-- <a-button type="link" size="small" @click="handleView(record as any)"> 查看 </a-button> -->
                            <a-popconfirm
                                title="确定要删除吗？"
                                ok-text="确定"
                                cancel-text="取消"
                                @confirm="handleDelete(record as any)"
                            >
                                <a-button type="link" size="small" danger>删除</a-button>
                            </a-popconfirm>
                        </a-space>
                    </template>
                </template>
            </a-table>
        </a-card>

        <!-- 表单对话框 -->
        <FormModal v-model:open="formModalVisible" :record="editingRecord" @success="handleFormSuccess" />
    </div>
</template>
<script lang="ts" setup>
import { useRequest } from "alova/client";
import { message, type TableProps } from "ant-design-vue";

import type { CategoryEntity } from "@/api/globals";
import { DateTimeUtils } from "@/utils/DateTimeUtils";

import FormModal from "./FormModal.vue";

// 新增响应式变量
const formModalVisible = ref(false);
const editingRecord = ref<CategoryEntity | null>(null);

const page = ref(1);
const pageSize = ref(10);
const total = ref(0);

const searchForm = reactive({
    name: "",
    code: ""
});

const handleSearch = async () => {
    await send(searchForm, 1);
    Object.keys(searchForm).forEach(key => {
        // @ts-ignore
        searchForm[key] = "";
    });
};
const handleReset = () => {
    Object.keys(searchForm).forEach(key => {
        // @ts-ignore
        searchForm[key] = "";
    });
    send();
};

// 列表列
const columns: TableProps["columns"] = [
    {
        title: "序号",
        dataIndex: "index",
        key: "index", // 列的key，默认为dataIndex
        customRender: row => {
            // 连续序号 = (当前页码 - 1) * 每页条数 + 当前行索引 + 1
            return (page.value - 1) * pageSize.value + row.index + 1;
        },
        width: 80,
        align: "center"
    },
    {
        title: "分类名称",
        dataIndex: "name"
    },
    {
        title: "代码",
        dataIndex: "code",
        width: "20%"
    },
    {
        title: "描述",
        dataIndex: "description",
        ellipsis: true
    },
    {
        title: "创建时间",
        dataIndex: "createdAt",
        key: "createdAt",
        customRender: row => DateTimeUtils.formatDateTime(row.record.createdAt),
        width: 180
    },
    {
        title: "操作",
        dataIndex: "action",
        key: "action",
        width: 200,
        fixed: "right",
        align: "center"
    }
];

const { data, loading, send } = useRequest(
    (searchForm = {}, current: number = 1, size: number = 10) => {
        // 过滤空值请求参数
        Object.keys(searchForm).forEach(item => {
            if (searchForm[item] === null || searchForm[item] === undefined || searchForm[item] === "") {
                Reflect.deleteProperty(searchForm, item);
            }
        });
        return Apis.CategoryAdmin.page({ params: { size, current, ...searchForm } });
    },
    { initialData: { data: { list: [] } } }
).onSuccess(res => {
    page.value = res.data.data.current;
    pageSize.value = res.data.data.size;
    total.value = res.data.data.total;
});

const pagination = computed<TableProps["pagination"]>(() => ({
    showSizeChanger: true,
    defaultPageSize: 10,
    // showTotal: (total, range) => `共 ${total} 条数据`,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    showLessItems: true,
    total: total.value,
    current: page.value,
    pageSize: pageSize.value
}));

// 	分页、排序、筛选变化时触发
const handleTableChange: TableProps["onChange"] = (pag, _filters, _sorter) => {
    const { current, pageSize } = pag;
    send(searchForm, current, pageSize);
};

// 表格操作

// 打开新增
const handleAdd = () => {
    editingRecord.value = null;
    formModalVisible.value = true;
};

// 打开编辑
const handleEdit = (record: CategoryEntity) => {
    editingRecord.value = record;
    formModalVisible.value = true;
};

// 表单提交成功后刷新表格
const handleFormSuccess = () => {
    message.success("操作成功");
    // 重新拉取最新数据（避免缓存）
    send({ time: Date.now() }, page.value, pageSize.value);
};

const handleView = (record: CategoryEntity) => {
    console.log("record", record);
};

const handleDelete = async (record: CategoryEntity) => {
    await Apis.CategoryAdmin.remove({
        pathParams: {
            id: record.id
        }
    });
    message.success("删除成功");
    // 添加时间参数，击穿缓存，拉取最新数据
    send({ time: Date.now() }, page.value, pageSize.value);
};
</script>
